using System;
using System.Web;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using log4net.Repository.Hierarchy;

namespace host
{
    public static class _Log
    {
        internal static void Bootstrap()
        {
        	RootLogger.AddAppender(CreateRollingFileAppender(Level.All, HttpContext.Current.Server.MapPath("~/Logs")));
            RootLogger.Repository.Configured = true;
        }

        internal static Logger RootLogger
        {
            get { return ((Hierarchy) LogManager.GetRepository()).Root; }
        }

        internal static RollingFileAppender CreateRollingFileAppender(Level level, string inputFolder)
        {
            var usingFileName = string.Format(
                "{4}\\host_{0}-{1}-{2}_{3}.log",
                DateTime.Today.Year, 
                DateTime.Today.Month, 
                DateTime.Today.Day, 
                level.Name,
                inputFolder);

            var layout = new PatternLayout("%date{MM/dd/yy HH:mm} [%level] %message%newline");

            var rollingFileAppender =
            new RollingFileAppender
                {
                    LockingModel = new FileAppender.MinimalLock(),
                    Layout = layout,
                    AppendToFile = true,
                    RollingStyle = RollingFileAppender.RollingMode.Date,
                    File = usingFileName,
                    ImmediateFlush = true,
                    Threshold = level
                };

            rollingFileAppender.ActivateOptions();

            return rollingFileAppender;
        }

        private static Logger GetLog()
        {
            if (!RootLogger.Repository.Configured) _Log.Bootstrap();

            return RootLogger;
        }

        public static void Info(string message)
        {
            GetLog().Log(Level.Info, message, null);
        }

        public static void InfoFormat(string format, params object[] parameters)
        {
            Info(string.Format(format, parameters));
        }

        public static void Error(string message)
        {
            GetLog().Log(Level.Error, message, null);
        }

        public static void ErrorFormat(string format, params object[] parameters)
        {
            Info(string.Format(format, parameters));
        }

        public static void Error(Exception exception)
        {
            GetLog().Log(Level.Error, exception.Message, exception);
        }

        public static void Warning(Exception exception)
        {
            GetLog().Log(Level.Warn, exception.Message, null);
        }

        public static void WarningFormat(string message, params object[] objs)
        {
            message = string.Format(message, objs);
            GetLog().Log(Level.Warn, message, null);
        }
    }
}